//
//  TSFoundPasswordViewController.swift
//  TopStock
//
//  Created by dyd on 2017/8/8.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit

class TSFoundPasswordViewController: UIViewController {
    @IBOutlet weak var getVerifyButton: UIButton!
    @IBOutlet weak var telPhoneNumTextField: UITextField!
    @IBOutlet weak var verifyTextField: UITextField!
    var isFromSetting:Bool = false
    @IBOutlet weak var nextButton: UIButton!
    private var timer: Timer?
    let tsRequest = TSRequestData()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavBarAppearance()
    }
    
    func setNavBarAppearance()
    {
        let navBar=UINavigationBar.appearance()
        navBar.titleTextAttributes = NavBarTitleTextAttributes
        navBar.tintColor = UIColor.black
        navBar.barTintColor = BarTintColor
        UIApplication.shared.statusBarStyle = .lightContent
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backItemAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    
    func telPoneNumDetection() ->Bool
    {
        let telPhoneNum = telPhoneNumTextField.text
        if (telPhoneNum?.isEmpty)!{
            showAlertView(title: nil, message: "请输入手机号码")
            return false
        }
        let isTelNumbe = TSMobileNumberManger.isTelPhoneNumber(telNumber: telPhoneNumTextField.text!)
        if (!isTelNumbe){
            showAlertView(title: nil, message: "请输入正确手机号码")
            return false
        }else{
            return true
        }
    }
    
    //MARK: - 获取验证码
    @IBAction func getVerifyAction(_ sender: UIButton) {
        if telPoneNumDetection(){
            getVerifyButton.backgroundColor = BtnTimingBackColor
            getVerifyButton.isEnabled = false
            self.remainingSeconds = 59
            self.isCommence = !self.isCommence
            if getVerifyCode(){
                let alertController = UIAlertController(title: "验证码已发送",
                                                        message: nil, preferredStyle: .alert)
                self.present(alertController, animated: true, completion: nil)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                    self.presentedViewController?.dismiss(animated: false, completion: nil)
                }
            }
        }
    }
    
    
    @IBAction func nextAction(_ sender: UIButton)
    {
        let isTelNum = telPoneNumDetection() as Bool
        if !isTelNum{
            return
        }
        let isVerify = verifyTextField.text?.isEmpty
        if (isVerify)!{
            showAlertView(title: nil, message: "请输入验证码")
            return
        }
        if isTelNum && !isVerify!{
            let verifyCodeDic = checkVerifyCode()
            let codeISOK = verifyCodeDic["success"] as! Bool
            if codeISOK{
                let data = verifyCodeDic["data"] as! NSDictionary
                showNextView(resetPwdToken: data["resetPwdToken"] as! String)
            }else{
                let error = verifyCodeDic["error"] as! NSDictionary
                showAlertView(title: nil, message: error["errorInfo"] as? String)
            }
        }
    }
    
    //获取验证码
    func getVerifyCode() ->Bool
    {
        let phoneNum = telPhoneNumTextField.text
        let requestDic = tsRequest.getCode(phoneNumber: phoneNum!, verify_type: 1)//modify
        return requestDic["success"] as! Bool
//        let phoneNum = telPhoneNumTextField.text
//        if getAccessToken(){
//            let requestDic = tsRequest.getCode(phoneNumber: phoneNum!)
//            return requestDic["success"] as! Bool
//        }else{
//            showAlertView(title: nil, message: "该号码还未注册过，请先注册")
//            return false
//        }
    }
    
    //如果注册过的账号会有Access Token
    public func getAccessToken() ->Bool{
        let accessToken = tsRequest.getAccessToken()
        if accessToken == nil{
            return false
        }else{
            return true
        }
    }
    
    //检验验证码
    func checkVerifyCode() ->NSDictionary
    {
        let phoneNum = telPhoneNumTextField.text
        let verifyCode = verifyTextField.text
        let requestDic = tsRequest.checkVerifyCode(phoneNumber: phoneNum!, verifyCcode: verifyCode!,verify_type: 1)
        return requestDic

    }
    
    //MARK - 计时器
    //倒计时的时间计算器
    private var isCommence: Bool = false {//是否开始计时
        willSet(newValue) {
            if newValue {
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
            } else {
                timer?.invalidate()
                timer = nil
            }
        }
    }
    
    //倒计时数
    private var remainingSeconds: Int = 0 {//remainingSeconds数值改变时 江将会调用willSet方法
        willSet(newSeconds) {
            let seconds = newSeconds%60
            getVerifyButton.setTitle(NSString(format: "%02ds", seconds) as String, for: .normal)
        }
    }
    
    // 更新时间
    func updateTimer(timer: Timer) {
        if remainingSeconds > 0 {
            remainingSeconds -= 1
        }
        if remainingSeconds == 0 {
            getVerifyButton.setTitle("获取验证码", for: .normal)
            getVerifyButton.isEnabled = true
            getVerifyButton.backgroundColor = BtnBackColor
            isCommence = !isCommence
            timer.invalidate()
        }
    }
    
    
    func showNextView(resetPwdToken:String)
    {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PasswordConfirmViewController") as! TSPasswordConfirmViewController
        if isFromSetting{
            nextViewController.title = "修改密码"
        }else{
            nextViewController.title = "确认密码"
        }
        nextViewController.isFromSetting = isFromSetting
        nextViewController.resetPwdToken = resetPwdToken
        self.navigationController?.pushViewController(nextViewController, animated: true)
    }
    
    //Alert的显示
    func showAlertView(title:String?,message:String?)
    {
        let alertController = UIAlertController(title: title,
                                                message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: {
            action in
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
